package com.acwing.partition43;

import java.io.*;

/**
 * @author rkc
 * @date 2022/7/4 16:40
 */
public class AC4277区块反转 {

    private static final int N = 100010;
    private static int[] d = new int[N], ne = new int[N], q = new int[N];
    private static int n, m, h;

    private static StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    private static PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        h = nextInt(); n = nextInt(); m = nextInt();
        for (int i = 0; i < n; i++) {
            int addr = nextInt(), data = nextInt(), next = nextInt();
            d[addr] = data;
            ne[addr] = next;
        }
        int cnt = 0;
        for (int i = h; i != -1; i = ne[i]) q[cnt++] = i;
        reverse(q, 0, cnt - 1);
        for (int i = cnt - 1; i >= 0; i -= m) reverse(q, Math.max(0, i - m + 1), i);
        for (int i = 0; i < cnt; i++) {
            int addr = q[i], next = q[i + 1];
            writer.format("%05d %d ", addr, d[addr]);
            if (i == cnt - 1) writer.println("-1");
            else writer.format("%05d\n", next);
        }
        writer.flush();
    }

    private static void reverse(int[] a, int l, int r) {
        while (l < r) {
            int t = a[l];
            a[l++] = a[r];
            a[r--] = t;
        }
    }

    private static int nextInt() throws IOException {
        tokenizer.nextToken();
        return (int) tokenizer.nval;
    }
}
